package com.delayqueue.common.netty.handler;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import io.netty.util.CharsetUtil;

import java.nio.charset.Charset;

public class StringToByteEncoder extends MessageToByteEncoder<String> {
    private Charset charset;

    public StringToByteEncoder() {
        this.charset = CharsetUtil.UTF_8;
    }

    public StringToByteEncoder(Charset charset) {
        this.charset = charset;
    }

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, String s, ByteBuf buf) throws Exception {
        byte[] bs = s.getBytes(charset);
        int len = bs.length + 4;
        ByteBuf bf = Unpooled.buffer(len, len);
        bf.writeInt(bs.length);
        bf.writeBytes(bs);
        buf.writeBytes(bf);
    }
}
